#!/usr/bin/env perl
#
# Create .mesh/.ele file from a Gmsh .msh file
# 
# For the wrekagrid project,
# Basile Clout, November 2007
#

use strict;
use warnings;

use File::Basename;

my $cnt_ele=0;
my @arr_ele=();
my $cnt_node=0;
my @arr_node=();
my @loc=();
my ($e, $n)=(0,0);
my $prefix="test";

if (length(@ARGV)==1){
	my ($left, $right)=split /\./, basename($ARGV[0]);
	open(SIN, "$ARGV[0]");
	$prefix = $left;
}else{
	die "Usage: ./gmsh2mesh.pl [.msh file].\n";
}

while (<SIN>) {

	chomp;
	if ($_ eq "\$Elements"){
		$cnt_ele++;
		next;
	}elsif ($_ eq "\$EndElements"){
		$cnt_ele=0;
		next;
	}elsif ($_ eq "\$Nodes"){
		$cnt_node++;
		next;
	}elsif ($_ eq "\$EndNodes"){
		$cnt_node=0;
		next;
	}
	
	if($cnt_ele>0){
		if($cnt_ele>1){
			@loc = split / /, $_;
			if ($loc[1] eq "2"){
				$arr_ele[$e]=[$loc[6], $loc[7], $loc[8]];
				$e++;
			}
		}
		$cnt_ele++;
	}elsif($cnt_node>0){
		if($cnt_node>1){
			@loc = split / /, $_;
#			print "cnt $cnt_node, node $n: $loc[1] $loc[2] $loc[3]\n";
			$arr_node[$n]=[$n+1, $loc[1], $loc[2], $loc[3]];
			$n++;
		}
	$cnt_node++;
	}	
}

open (MESH, ">${prefix}.mesh") or die("Impossible to create file ${prefix}.mesh: $!");
open (NODE, ">${prefix}.node") or die("Impossible to create file ${prefix}.node: $!");

print MESH "$e 1\n";
foreach my $row (@arr_ele){
	print MESH join(' ',@$row), "\n";
}
print "${prefix}.mesh successfully created.\n";

print NODE "$n 3\n";
foreach my $row (@arr_node){
	print NODE join(' ', @$row), "\n";
}
print "${prefix}.node successfully created.\n";
